// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env:"yiliaojiufeng-6gt0kj1l1df8b7b7",
  traceUser: true,
})
const db =cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContent = cloud.getWXContext();
  var flag = await db.collection('user').where({
    _openid: wxContent.OPENID
  }).get();
  console.log(flag.data.length);
  if (flag.data.length == 0) {//新用户 添加到数据库
    try {
      return await db.collection('user').add({
        data: {
          username: event.username,
          userimage: event.userimage,
          _openid: wxContent.OPENID,
        }
      })
    } catch(e) {
      console.error(e)
    }
  }
  else{//老用户 更新数据库
    try {
      return await db.collection('user').where({
        _openid: wxContent.OPENID
      })
      .update({
        data: {
          username: event.username,
          userimage: event.userimage,
          userintro: event.userintro,
        },
      })
    } catch(e) {
      console.error(e)
    }
  }
}